<script>
/**
 * 给每个视图一个名字
 */
import {DEFINITION, VIEW, Views} from '@/store/views'
/**
 * 这是个具有路由功能的组件,
 *     根据store的数据渲染由layer指定图层
 *     通过 this.$store.dispatch('reView', { layer, url })来更新视图
 */
export default {
  name: 'YmRouter',
  created () {
    this.$store.commit('setupView', this.layer)
  },
  beforeDestroy () {
    this.$store.commit('dropView', this.layer)
  },
  render (createElement) {
    const props = this.definition
    const on = this.event
    return createElement(this.view, {
      props,
      attrs: props,
      on
    })
  },
  computed: {
    /**
       * 视图名称
       */
    view () {
      const name = this.$store.state.views[this.layer][VIEW]
      return Views[name] || name
    },
    /**
       * 视图定义
       */
    definition () {
      const vm = this
      return {
        ...vm.$store.state.views[this.layer][DEFINITION],
        ...vm.$attrs
      }
    },
    /**
       * 事件处理
       */
    event () {
      const vm = this
      return {
        ...vm.$store.state.views[this.layer].event,
        ...vm.$listeners
      }
    }
  },
  props: {
    /**
       * 视图层
       */
    layer: {
      type: String,
      default: 'main'
    },
    /**
       * 事件等的命名空间
       */
    ns: {
      type: String,
      default: ''
    }
  },
  methods: {
    async redirect ({ url, layer = this.layer }) {
      (this.layer + '') === (layer + '') && await this.$store.dispatch('reloadViewByUrl', {
        layer,
        url
      })
    }
  }
}
</script>
